package pe.com.ValoracionVivienda.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import pe.com.ValoracionVivienda.container.AppContainer;
import pe.com.ValoracionVivienda.domain.entities.Usuario;
import pe.com.ValoracionVivienda.security.AESEncryption;
import pe.com.ValoracionVivienda.security.SHACryptographic;
import pe.com.ValoracionVivienda.service.impl.UsuarioServiceJpaImpl;
import pe.com.ValoracionVivienda.service.interfaces.UsuarioService;

public class ShellLogin extends Shell {
	private Text txtUsuario;
	private Text txtPassword;
	private Label lblMensaje;
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Display display = Display.getDefault();
			ShellLogin shell = new ShellLogin(display);
			shell.open();
			shell.layout();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the shell.
	 * @param display
	 */
	public ShellLogin(Display display) {
		super(display, SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.TITLE);
		
		Label lblNewLabel = new Label(this, SWT.NONE);
		lblNewLabel.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
		lblNewLabel.setBounds(222, 87, 155, 20);
		lblNewLabel.setText("Informaci\u00F3n de Usuario");
		
		Label lblNewLabel_1 = new Label(this, SWT.NONE);
		lblNewLabel_1.setBounds(141, 134, 40, 15);
		lblNewLabel_1.setText("Usuario");
		
		Label lblContrasea = new Label(this, SWT.NONE);
		lblContrasea.setText("Contrase\u00F1a");
		lblContrasea.setBounds(141, 164, 60, 15);
		
		txtUsuario = new Text(this, SWT.BORDER);
		txtUsuario.setBounds(222, 131, 223, 21);
		
		txtPassword = new Text(this, SWT.BORDER | SWT.PASSWORD);
		txtPassword.setBounds(222, 161, 223, 21);
		
		Button btnIngresar = new Button(this, SWT.NONE);
		btnIngresar.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				loginUsuario();
			}
		});
		btnIngresar.setBounds(278, 215, 75, 25);
		btnIngresar.setText("Ingresar");
		
		Button btnSalir = new Button(this, SWT.NONE);
		btnSalir.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				salirSistema();
			}
		});
		btnSalir.setText("Salir");
		btnSalir.setBounds(370, 215, 75, 25);
		
		Label lblSistemaPrediccionPrecios = new Label(this, SWT.NONE);
		lblSistemaPrediccionPrecios.setText("SISTEMA PREDICCION PRECIOS PREDIOS");
		lblSistemaPrediccionPrecios.setFont(SWTResourceManager.getFont("Calibri", 11, SWT.NORMAL));
		lblSistemaPrediccionPrecios.setBounds(117, 43, 243, 18);
		
		Label lblNewLabel_2 = new Label(this, SWT.NONE);
		lblNewLabel_2.setImage(SWTResourceManager.getImage(ShellLogin.class, "/pe/com/ValoracionVivienda/images/lockoverlay.png"));
		lblNewLabel_2.setBounds(45, 119, 60, 60);
		setDefaultButton(btnIngresar);
		
		lblMensaje = new Label(this, SWT.NONE);
		lblMensaje.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		lblMensaje.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD));
		lblMensaje.setBounds(141, 190, 202, 17);
		lblMensaje.setText("Usuario o contrase\u00F1a incorrectos");
		lblMensaje.setVisible(false);
		createContents();
		centrarEnPantalla(display);
	}

	protected void salirSistema() {
		this.getDisplay().dispose();
		this.dispose();
	}

	protected void loginUsuario() {
		String nickname = txtUsuario.getText();
		String password = txtPassword.getText();
		
		UsuarioService usuarioService = new UsuarioServiceJpaImpl();
		Usuario usuario = usuarioService.getUsuarioPorNickname(nickname);
		usuarioService.close();
		
		if (usuario == null)
			lblMensaje.setVisible(true);
		else{
			if (usuario.getCuentaActiva()){
				try {
					String seed = AESEncryption.descifrar(usuario.getSeed());
					String passwordGenerado = SHACryptographic.criptografiar(password, seed);
					if (usuario.getPassword().equals(passwordGenerado)){
						AppContainer.ID_USUARIO = usuario.getId();
						navegarVentanaPrincipal();
					} else
						lblMensaje.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (usuario.getPassword().equals(password)){
				AppContainer.ID_USUARIO = usuario.getId();
				navegarVentanaPrincipal();
			} else 
				lblMensaje.setVisible(true);
		}
	}

	private void navegarVentanaPrincipal() {
		this.close();
		this.dispose();
		ShellPrincipal shell = new ShellPrincipal(Display.getDefault());
		shell.open();
		while (!shell.isDisposed()) {
			if (!shell.getDisplay().readAndDispatch()) {
				shell.getDisplay().sleep();
			}
		}
		shell.dispose();
	}

	/**
	 * Create contents of the shell.
	 */
	protected void createContents() {
		setText("Login");
		setSize(480, 282);
	}
	
	private void centrarEnPantalla(Display display){
		Monitor primary = display.getPrimaryMonitor();
	    Rectangle bounds = primary.getBounds();
	    Rectangle rect = getBounds();
	    
	    int x = bounds.x + (bounds.width - rect.width) / 2;
	    int y = bounds.y + (bounds.height - rect.height) / 2;
	    setLocation(x, y);
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
